<template>
  <div ref="kefubox" class="chat-container">
    <!-- Chat messages -->
    <!-- 在Vue模板中修改v-bind:class指令 -->
    <div v-for="message in chatHistory" :key="message.id" :class="[
  'chat-message',
  message.role === 'user' ? 'right-avatar' : 'left-avatar'
]">
      <img :src="getAvatarSrc(message.role)" alt="avatar" class="avatar">
      <div class="message-content" v-html="message.content"></div>
    </div>

    <!-- Input box -->
    <div class="input-box">
      <input v-model="userLastInput" @keyup.enter="sendMessage" :disabled="disabled" placeholder="Type a message...">
      <button @click="sendMessage" :disabled="disabled">发送</button>
    </div>
  </div>
</template>

<script>
import useFormatMarkdown from '../../utils/useFormatMarkdown.js';
import userAvatar from '@/assets/images/assiant.png';
import axios from "axios";
// import { Message } from "element-plus";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      userLastInput: '',
      chatHistory: [],
      disabled: false
    };
  },
  // computed: {
  //   dialogVisible: {
  //     get() {
  //       return this.visible;
  //     },
  //     set(val) {
  //       this.$emit('update:visible', val);
  //     }
  //   }
  // },
  mounted() {
    const savedHistory = localStorage.getItem('chatHistory');
    if (savedHistory) {
      this.chatHistory = JSON.parse(savedHistory).map(msg => ({
        ...msg,
        content: msg.role === 'system' ? useFormatMarkdown(msg.content) : msg.content
      }));
    }
  },
  beforeDestroy() {
    localStorage.setItem('chatHistory', JSON.stringify(this.chatHistory));
  },
  methods: {
    getAvatarSrc(role) {
      const userAvatarPath = this.$store.state.user.avatar;

      return role === 'user' ? userAvatarPath : userAvatar;
    },
    async sendMessage() {
      const userInput = this.userLastInput.trim();
      if (!userInput) {
        // Message.warning('Please enter your question!!!');
        this.$message.warning('Please enter your question!!!')
        return;
      }
      if (!this.$store.state.user) {
        // Message.warning('Please log in before using!!!');
        this.$message.warning('Please log in before using!!!')
        return;
      }
      this.disabled = true;

      const userMessage = {
        role: 'user',
        content: userInput,
        id: Date.now().toString(),
      };
      this.addMessage(userMessage);

      try {
        console.log(this.chatHistory,'this.chatHistory')
        const response = await axios({
          url: 'http://localhost:3300/assiant',
          method: 'post',
          data: {
            prompt: this.chatHistory.concat(userMessage),
            user_message: this.userLastInput,
          },
          onDownloadProgress: ({ event }) => {
            this.userLastInput = '';
            const xhr = event.target;
            const { responseText } = xhr;
            this.handleStreamData(responseText);
          }
        });

      } catch (error) {
        const systemReply = {
          role: 'system',
          content: useFormatMarkdown('perminute limit reached, please try again later!!!'),
          id: Date.now().toString(),
        };
        this.addMessage(systemReply);
        console.log('Error during chat process:', error);
      }
    },
    handleStreamData(responseText) {
      const arr = responseText.split("\n\r").filter(item => item !== "");
      const item = arr[arr.length - 1];
      try {
        const p = JSON.parse(item);
        if (p.code && p.code === 500) {
          const systemReply = {
            role: 'system',
            content: useFormatMarkdown('perdayMinute limit reached, please try again later!!!'),
            id: Date.now().toString(),
          };
          this.addMessage(systemReply);
          this.disabled = false;
        }
        const systemReply = {
          role: 'system',
          content: useFormatMarkdown(p.total),
          id: Date.now().toString(),
        };
        this.addMessage(systemReply);
        this.disabled = false;
      } catch (error) {
        console.error('Error parsing stream data:', error);
      }
    },
    addMessage(message) {
      this.chatHistory.push(message);
      localStorage.setItem('chatHistory', JSON.stringify(this.chatHistory));
      this.scrollToBottom();
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.kefubox;
        container.scrollTop = container.scrollHeight;
      });
    }
  },
  // watch: {
  //   dialogVisible(newValue) {
  //     if (newValue) {
  //       this.scrollToBottom();
  //     }
  //   }
  // }
};
</script>

<style scoped>
.chat-container {
  border: 1px solid #ccc;
  padding: 10px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  min-height: 700px; /* 使用最小高度而不是固定高度 */
  overflow-y: auto; /* 确保有滚动条 */
  width: 1200px;
  margin-left: 200px;
}

.chat-message {
  display: flex;
  margin-bottom: 10px;
}

.chat-message.user .avatar {
  order: 2;
}

.chat-message.system .avatar {
  order: 1;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;

}

.message-content {
  max-width: 70%;
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 5px;
}


.input-box input {
  width: 70%;
  padding: 5px;
  margin-right: 10px;
}

.input-box button {
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.input-box button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
/* 添加一些基本的重置样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.chat-container {
  height: 400px;
  overflow-y: auto;
  border: 1px solid #ccc;
  padding: 10px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

/* 美化滚动条 */
.chat-container::-webkit-scrollbar {
  width: 8px;
}

.chat-container::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 4px;
}

.chat-container::-webkit-scrollbar-track {
  background-color: transparent;
}

/* 基本的聊天消息容器样式 */
.chat-message {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

/* 左侧头像和消息内容样式 */
.chat-message.left-avatar {
  justify-content: flex-start;
}

.chat-message.left-avatar .avatar {
  order: 1;
}

.chat-message.left-avatar .message-content {
  order: 2;
  margin-left: 10px;
}

/* 右侧头像和消息内容样式 */
.chat-message.right-avatar {
  justify-content: flex-end;
}

.chat-message.right-avatar .avatar {
  order: 2;
}

.chat-message.right-avatar .message-content {
  order: 1;
  margin-right: 10px;
}

/* 头像样式 */
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

/* 消息内容样式 */
.message-content {
  padding: 10px;
  border-radius: 10px;
  max-width: 70%;
  word-wrap: break-word;
}

/* 用户消息内容的背景颜色 */
.chat-message.right-avatar .message-content {
  background-color: #007BFF;
  color: white;
}

/* AI消息内容的背景颜色 */
.chat-message.left-avatar .message-content {
  background-color: #EAEAEA;
  color: black;
}

/* 确保用户的消息内容背景颜色与系统的不同 */
.chat-message.user .message-content {
  background-color: #dcf8c6;
}

.input-box {
  margin-top: 100px;
  display: flex;
  align-items: center;
}

.input-box input {
  flex-grow: 1;
  padding: 10px;
  margin-right: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  outline: none;
}

.input-box button {
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.input-box button:hover {
  background-color: #0056b3;
}

.input-box button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  pointer-events: none;
}

/* 适配移动设备 */
@media (max-width: 768px) {
  .chat-container {
    height: 300px;
    padding: 5px;
  }

  .message-content {
    max-width: 80%;
    font-size: 12px;
  }

  .input-box input {
    padding: 8px;
  }

  .input-box button {
    padding: 8px 10px;
    font-size: 14px;
  }
}
</style>
